--
-- Author: yawei.zhu
-- Date: 2018-09-11 11:06:56
--
-- DynastyBattleModel
--

local DynastyBattleTownInfo = import(".DynastyBattleTownInfo")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

local _TEST = false

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
end

function ClassRef:setDynastyBattleID(townId, strongholdId)
	self._townId = townId
	self._strongholdId = strongholdId
end

function ClassRef:getTownPhases()
	return self._townPhases
end

function ClassRef:getPhaseByTownId(townId) 
	if not self._townPhases or not self._townPhases[townId]  then return "CLOSE" end
	local townInfo = self._townPhases[townId]
	return townInfo.phase
end

------------------------ receive ------------------------
function ClassRef:onEnterTownWar(msg)
	if msg.ok then
		display.pushToast(L("lua_code_text_179"))
	else
		display.pushToast(L("lua_code_text_410"))
	end
end

-- 公会战结算
function ClassRef:onDynastyBattleAccount(msg)
	app:sendMsg("DynastyBattleController", "showDynastyAccount", msg)
end

-- 服务器通知城镇状态
function ClassRef:onTownPhaseNotify(msg)
	-- dump(msg, "onTownPhaseNotify")
	local infos = {}

	for _, info in ipairs(msg.infos) do
		local value = {}
		value.townId = info.townId
		value.phase = info.phase
		infos[value.townId] = value
	end
	self._townPhases = infos

	-- 创建 或 移除 npc
	NpcFactory:createActivityNpcById(Enums.activityNpcType.dynasty)
end

------------------------ request ------------------------
function ClassRef:reqGetTownInfo(townId, cb)
	if _TEST then
		local townInfo = DynastyBattleTownInfo.new()
		townInfo:test()
		app:sendMsg("DynastyBattleController", "updateTownInfo", townInfo)
		executeFunc(cb, townInfo)
		return
	end

	if not townId then return end
	print("reqGetTownInfo", townId)
	app.session:request("pb_town.C2S_TownInfo", {townId = townId}, function(msg)
		-- dump(msg.town, "onReqGetTownInfo")
		local townInfo
		if msg.town then
			townInfo = DynastyBattleTownInfo.new(msg.town)
			app:sendMsg("DynastyBattleController", "updateTownInfo", townInfo)
		end
		executeFunc(cb, townInfo)
	end)
end

-- 请求进入公会战场
function ClassRef:reqEnterDynastyBattle()
	if not self._townId or not self._strongholdId then return end

	print("reqEnterDynastyBattle", self._townId, self._strongholdId)
	app.session:request("pb_town.C2S_EnterTownWar", {id = self._townId, strongholdId = self._strongholdId})
end

return ClassRef
